package com.litaomn.fang.hotload.server;

import android.os.PowerManager;
import android.os.SystemClock;

import com.google.common.base.Preconditions;


import org.apache.commons.lang3.time.DateFormatUtils;

import java.net.URI;
import java.util.Map;

public class WebSocketManager {


    private WebSocket webSocket;

    private static WebSocketManager mInstance;

    private WebSocketManager() {
    }

    public static WebSocketManager getInstance() {
        if (mInstance == null) {
            mInstance = new WebSocketManager();
        }
        return mInstance;
    }

    public void connect(Map map) {
        String host = null;
        String port = null;
        if (map.get("host") != null) {
            host = (String) map.get("host");
        }
        if (map.get("port") != null) {
            port = (String) map.get("port");
        }
        Preconditions.checkNotNull(host, "host不能为空");
        Preconditions.checkNotNull(port, "port不能为空");
        webSocket = new WebSocket(URI.create("ws://" + host + ":" + port));
        webSocket.connect();
    }

    public void send() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    if (webSocket.isOpen()) {
                        webSocket.send(DateFormatUtils.format(System.currentTimeMillis(),
                                DateFormatUtils.ISO_8601_EXTENDED_TIME_FORMAT.getPattern()));
                    }
                    SystemClock.sleep(3000);
                }
            }
        }).start();
    }

}
